package com.yc.star.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.yc.star.entity.User;
import com.yc.star.mapper.UserMapper;
import com.yc.star.service.IUService;
import com.yc.star.service.IUserService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author ljl
 * @since 2024-06-13
 */
@Service
public class UServiceImpl extends ServiceImpl<UserMapper, User> implements IUService {

    @Resource
    UserMapper userMapper;



    /**
     * 根据标签搜索用户 (内存查询过滤)
     * @param tagsNameList 用户要拥有的标签
     * @return
     */
    @Override
    public List<User> searchUserByTags(List<String> tagsNameList){
        if (CollectionUtils.isEmpty(tagsNameList)){
            //报错
            throw new RuntimeException("Please select");
        }
        // 1. 先查询所有用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        List<User> userList = userMapper.selectList(queryWrapper);
        Gson gson = new Gson();
        // 2. 再判断是否包含要求的标签
        return userList.stream().filter(user -> {
            String tagsStr = user.getTags();
            //反序列化 获取标签列表
            Set<String> tempTagNameSet = gson.fromJson(tagsStr, new TypeToken<Set<String>>() {
            }.getType());
            tempTagNameSet = Optional.ofNullable(tempTagNameSet).orElse(new HashSet<>());
            for (String tagName : tagsNameList) {
                if (!tempTagNameSet.contains(tagName)) {
                    return false;
                }
            }
            System.out.println(1);
            System.out.println(user);
            return true;
        }).collect(Collectors.toList());

    }



    /**
     * 根据标签搜索用户（SQL 查询版）
     *
     * @param tagNameList 用户要拥有的标签
     * @return
     */
    @Override
    public List<User> searchUsersByTagsBySQL(List<String> tagNameList) {
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new RuntimeException("No tags to search");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 拼接 and 查询
        // like '%Java%' and like '%Python%'
        for (String tagName : tagNameList) {
            queryWrapper = queryWrapper.like("tags", tagName);
        }
        List<User> userList = userMapper.selectList(queryWrapper);
        return userList.stream().collect(Collectors.toList());
    }


}
